<template>
  <div class="report-detail-view">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <el-button @click="goBack" circle>
            <el-icon><ArrowLeft /></el-icon>
          </el-button>
          <div class="title-info">
            <h2 v-if="currentReport">{{ currentReport.title }}</h2>
            <div v-if="currentReport" class="meta-info">
              <el-tag :type="getTypeTagType(currentReport.type)" size="small">
                {{ currentReport.typeDisplayName }}
              </el-tag>
              <el-tag :type="getStatusTagType(currentReport.status)" size="small">
                {{ currentReport.statusDisplayName }}
              </el-tag>
              <span class="version">v{{ currentReport.version }}</span>
              <span class="date">{{ formatDateTime(currentReport.createdAt) }}</span>
            </div>
          </div>
        </div>
        <div class="action-section">
          <el-button v-if="!isEditMode" @click="toggleEditMode">
            <el-icon><Edit /></el-icon>
            {{ $t('workReports.common.edit') }}
          </el-button>
          <el-button v-if="isEditMode" type="primary" @click="handleSave" :loading="saving">
            <el-icon><Check /></el-icon>
            保存
          </el-button>
          <el-button v-if="isEditMode" @click="handleCancel">
            <el-icon><Close /></el-icon>
            取消
          </el-button>
          <el-dropdown @command="handleDropdownCommand">
            <el-button>
              更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="export">
                  <el-icon><Download /></el-icon>
                  导出
                </el-dropdown-item>
                <el-dropdown-item command="duplicate">
                  <el-icon><CopyDocument /></el-icon>
                  复制
                </el-dropdown-item>
                <el-dropdown-item command="delete" divided>
                  <el-icon><Delete /></el-icon>
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>

    <!-- 报告内容 -->
    <div v-else-if="currentReport" class="report-content">
      <!-- 编辑模式 -->
      <div v-if="isEditMode" class="edit-mode">
        <el-card class="edit-card">
          <template #header>
            <div class="edit-header">
              <h3>编辑报告</h3>
              <div class="edit-actions">
                <el-button @click="showOriginalContent = !showOriginalContent" size="small">
                  {{ showOriginalContent ? '隐藏' : '显示' }}原始内容
                </el-button>
              </div>
            </div>
          </template>

          <el-form :model="editForm" label-width="80px">
            <el-form-item label="标题">
              <el-input v-model="editForm.title" placeholder="请输入报告标题" />
            </el-form-item>
            
            <el-form-item label="状态">
              <el-select v-model="editForm.status" placeholder="请选择状态">
                <el-option label="草稿" value="DRAFT" />
                <el-option label="最终版" value="FINAL" />
                <el-option label="已归档" value="ARCHIVED" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="标签">
              <el-select
                v-model="editForm.tags"
                multiple
                filterable
                allow-create
                placeholder="请选择或输入标签"
                style="width: 100%"
              >
                <el-option
                  v-for="tag in commonTags"
                  :key="tag"
                  :label="tag"
                  :value="tag"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="内容">
              <div class="content-editor">
                <MdEditor
                  v-model="editForm.editedContent"
                  :placeholder="'编辑报告内容...'"
                  :preview="true"
                  :toolbars="editorToolbars"
                  :theme="editorTheme"
                  language="zh-CN"
                  @onChange="handleContentChange"
                  @onSave="handleSave"
                />
              </div>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 原始内容对比 -->
        <el-card v-if="showOriginalContent" class="original-content-card">
          <template #header>
            <h3>AI原始生成内容</h3>
          </template>
          <MdPreview
            :key="`original-content-${currentReport?.id || Date.now()}`"
            :modelValue="currentReport?.originalContent || ''"
            :theme="previewTheme"
            language="zh-CN"
          />
        </el-card>
      </div>

      <!-- 查看模式 -->
      <div v-else class="view-mode">
        <el-card class="content-card">
          <template #header>
            <div class="content-header">
              <h3>报告内容</h3>
              <div class="content-actions">
                <el-button @click="copyContent" size="small">
                  <el-icon><DocumentCopy /></el-icon>
                  复制内容
                </el-button>
                <el-button @click="showOriginal = !showOriginal" size="small">
                  {{ showOriginal ? '显示编辑版' : '显示原始版' }}
                </el-button>
              </div>
            </div>
          </template>

          <MdPreview
            :key="`report-preview-${currentReport?.id || Date.now()}`"
            :modelValue="currentReport?.editedContent || currentReport?.originalContent || ''"
            :theme="previewTheme"
            language="zh-CN"
          />
        </el-card>

        <!-- 报告信息 -->
        <el-card class="info-card">
          <template #header>
            <h3>报告信息</h3>
          </template>
          
          <el-descriptions :column="2" border>
            <el-descriptions-item label="报告类型">
              <el-tag :type="getTypeTagType(currentReport.type)">
                {{ currentReport.typeDisplayName }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="报告状态">
              <el-tag :type="getStatusTagType(currentReport.status)">
                {{ currentReport.statusDisplayName }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="版本号">
              v{{ currentReport.version }}
              <el-tag v-if="currentReport.isEdited" size="small" type="warning" style="margin-left: 8px">
                已编辑
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="时间范围">
              {{ formatDate(currentReport.periodStart) }}
              <span v-if="currentReport.periodStart !== currentReport.periodEnd">
                至 {{ formatDate(currentReport.periodEnd) }}
              </span>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ formatDateTime(currentReport.createdAt) }}
            </el-descriptions-item>
            <el-descriptions-item label="更新时间">
              {{ formatDateTime(currentReport.updatedAt) }}
            </el-descriptions-item>
            <el-descriptions-item label="标签" :span="2">
              <el-tag
                v-for="tag in currentReport.tags"
                :key="tag"
                size="small"
                style="margin-right: 8px"
              >
                {{ tag }}
              </el-tag>
              <span v-if="!currentReport.tags || currentReport.tags.length === 0" class="no-data">
                暂无标签
              </span>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </div>
    </div>

    <!-- 错误状态 -->
    <div v-else class="error-state">
      <el-result icon="error" title="报告不存在" sub-title="请检查报告ID是否正确">
        <template #extra>
          <el-button type="primary" @click="goBack">返回列表</el-button>
        </template>
      </el-result>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft, Edit, Check, Close, ArrowDown, Download, CopyDocument,
  Delete, DocumentCopy
} from '@element-plus/icons-vue'
import { useWorkReportStore } from '@/stores/workReportStore'
import type { GeneratedReport, ReportUpdateRequest } from '@/types/workReport'
import { MdEditor, MdPreview } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import 'md-editor-v3/lib/preview.css'

const { t } = useI18n()
const route = useRoute()
const router = useRouter()
const workReportStore = useWorkReportStore()

// ==================== 响应式数据 ====================

const loading = ref(false)
const saving = ref(false)
const isEditMode = ref(false)
const showOriginalContent = ref(false)
const showOriginal = ref(false)

// 编辑表单
const editForm = ref<ReportUpdateRequest>({
  title: '',
  editedContent: '',
  status: 'DRAFT',
  tags: []
})

// 常用标签
const commonTags = ref(['重要', '紧急', '完成', '进行中', '待办', '总结', '计划'])

// ==================== 计算属性 ====================

const currentReport = computed(() => workReportStore.currentReport)

const reportId = computed(() => {
  const id = route.params.id
  return typeof id === 'string' ? parseInt(id) : 0
})

// 编辑器配置
const editorTheme = computed(() => {
  return document.documentElement.classList.contains('dark') ? 'dark' : 'light'
})

const previewTheme = computed(() => {
  return document.documentElement.classList.contains('dark') ? 'dark' : 'light'
})

const editorToolbars = [
  'bold', 'underline', 'italic', '-',
  'title', 'strikeThrough', 'sub', 'sup', 'quote',
  'unorderedList', 'orderedList', 'task', '-',
  'codeRow', 'code', 'link', 'image', 'table', '-',
  'revoke', 'next', 'save', '=',
  'pageFullscreen', 'fullscreen', 'preview', 'catalog'
]



// ==================== 方法 ====================

/**
 * 初始化页面
 */
const initPage = async () => {
  // 检查路由参数中的模式
  if (route.query.mode === 'edit') {
    isEditMode.value = true
  }
  
  await fetchReportDetail()
}

/**
 * 获取报告详情
 */
const fetchReportDetail = async () => {
  if (!reportId.value) {
    ElMessage.error('无效的报告ID')
    return
  }
  
  try {
    loading.value = true
    await workReportStore.fetchReportDetail(reportId.value)
    
    // 初始化编辑表单
    if (currentReport.value) {
      editForm.value = {
        title: currentReport.value.title,
        editedContent: currentReport.value.editedContent || currentReport.value.originalContent || '',
        status: currentReport.value.status,
        tags: currentReport.value.tags || []
      }
    }
  } catch (error) {
    console.error('获取报告详情失败:', error)
  } finally {
    loading.value = false
  }
}

/**
 * 切换编辑模式
 */
const toggleEditMode = () => {
  isEditMode.value = !isEditMode.value
  if (isEditMode.value && currentReport.value) {
    // 重新初始化编辑表单
    editForm.value = {
      title: currentReport.value.title,
      editedContent: currentReport.value.editedContent || currentReport.value.originalContent || '',
      status: currentReport.value.status,
      tags: currentReport.value.tags || []
    }
  }
}

/**
 * 保存报告
 */
const handleSave = async () => {
  if (!currentReport.value) return
  
  try {
    saving.value = true
    await workReportStore.updateReport(currentReport.value.id, editForm.value)
    isEditMode.value = false
    ElMessage.success('报告保存成功')
  } catch (error) {
    console.error('保存报告失败:', error)
  } finally {
    saving.value = false
  }
}

/**
 * 取消编辑
 */
const handleCancel = () => {
  isEditMode.value = false
  // 重置表单
  if (currentReport.value) {
    editForm.value = {
      title: currentReport.value.title,
      editedContent: currentReport.value.editedContent || currentReport.value.originalContent || '',
      status: currentReport.value.status,
      tags: currentReport.value.tags || []
    }
  }
}

/**
 * 下拉菜单命令处理
 */
const handleDropdownCommand = (command: string) => {
  switch (command) {
    case 'export':
      handleExport()
      break
    case 'duplicate':
      handleDuplicate()
      break
    case 'delete':
      handleDelete()
      break
  }
}

/**
 * 导出报告
 */
const handleExport = async () => {
  if (!currentReport.value) return
  
  try {
    await workReportStore.exportReport(currentReport.value.id, 'PDF')
  } catch (error) {
    console.error('导出报告失败:', error)
  }
}

/**
 * 复制报告
 */
const handleDuplicate = () => {
  ElMessage.info('复制功能开发中，敬请期待')
}

/**
 * 删除报告
 */
const handleDelete = async () => {
  if (!currentReport.value) return
  
  try {
    await ElMessageBox.confirm(
      `确定要删除报告"${currentReport.value.title}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await workReportStore.deleteReport(currentReport.value.id)
    ElMessage.success('报告删除成功')
    goBack()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除报告失败:', error)
    }
  }
}

/**
 * 复制内容
 */
const copyContent = async () => {
  if (!currentReport.value) return
  
  const content = showOriginal.value 
    ? currentReport.value.originalContent 
    : currentReport.value.currentContent
    
  try {
    await navigator.clipboard.writeText(content || '')
    ElMessage.success('内容已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}

/**
 * 插入Markdown语法
 */
/**
 * 编辑器内容变化处理
 */
const handleContentChange = (value: string) => {
  editForm.value.editedContent = value
}

/**
 * 返回上一页
 */
const goBack = () => {
  router.back()
}

// ==================== 工具方法 ====================

/**
 * 格式化日期显示
 */
const formatDate = (dateStr: string): string => {
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN')
}

/**
 * 格式化日期时间显示
 */
const formatDateTime = (dateTimeStr: string): string => {
  const date = new Date(dateTimeStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

/**
 * 获取类型标签类型
 */
const getTypeTagType = (type: string): string => {
  const typeMap: Record<string, string> = {
    'DAILY': 'primary',
    'WEEKLY': 'success',
    'MONTHLY': 'warning'
  }
  return typeMap[type] || 'info'
}

/**
 * 获取状态标签类型
 */
const getStatusTagType = (status: string): string => {
  const statusMap: Record<string, string> = {
    'DRAFT': 'info',
    'FINAL': 'success',
    'ARCHIVED': 'warning'
  }
  return statusMap[status] || 'info'
}

// ==================== 生命周期 ====================

onMounted(() => {
  initPage()
})
</script>

<style scoped lang="scss">
.report-detail-view {
  padding: 20px;
  background-color: var(--el-bg-color-page);
}

// 页面头部
.page-header {
  margin-bottom: 20px;

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 16px;

    .title-section {
      display: flex;
      align-items: flex-start;
      gap: 12px;
      flex: 1;

      .title-info {
        h2 {
          margin: 0 0 8px 0;
          font-size: 24px;
          color: var(--el-text-color-primary);
          font-weight: 600;
        }

        .meta-info {
          display: flex;
          align-items: center;
          gap: 8px;
          flex-wrap: wrap;

          .version {
            font-size: 12px;
            color: var(--el-text-color-regular);
            background-color: var(--el-fill-color-light);
            padding: 2px 6px;
            border-radius: 4px;
          }

          .date {
            font-size: 12px;
            color: var(--el-text-color-regular);
          }
        }
      }
    }

    .action-section {
      display: flex;
      gap: 8px;
      flex-shrink: 0;
    }
  }
}

// 加载容器
.loading-container {
  padding: 20px;
}

// 报告内容
.report-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

// 编辑模式
.edit-mode {
  .edit-card {
    .edit-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      h3 {
        margin: 0;
        font-size: 16px;
        color: var(--el-text-color-primary);
      }
    }

    .content-editor {
      position: relative;
      width: 100%;
      border: 1px solid var(--el-border-color);
      border-radius: 6px;
      overflow: hidden;

      :deep(.md-editor) {
        height: 500px;
        border: none;
      }
    }
  }

  .original-content-card {
    h3 {
      margin: 0;
      font-size: 16px;
      color: var(--el-text-color-primary);
    }
  }
}

// 查看模式
.view-mode {
  display: grid;
  grid-template-columns: 1fr 300px;
  gap: 20px;

  .content-card {
    .content-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      h3 {
        margin: 0;
        font-size: 16px;
        color: var(--el-text-color-primary);
      }

      .content-actions {
        display: flex;
        gap: 8px;
      }
    }
  }

  .info-card {
    h3 {
      margin: 0;
      font-size: 16px;
      color: var(--el-text-color-primary);
    }

    .no-data {
      color: var(--el-text-color-placeholder);
      font-style: italic;
    }
  }
}

// Markdown内容样式
.markdown-content {
  line-height: 1.6;
  color: var(--el-text-color-primary);

  :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
    margin: 16px 0 8px 0;
    color: var(--el-text-color-primary);
    font-weight: 600;
  }

  :deep(h1) { font-size: 24px; }
  :deep(h2) { font-size: 20px; }
  :deep(h3) { font-size: 18px; }
  :deep(h4) { font-size: 16px; }
  :deep(h5) { font-size: 14px; }
  :deep(h6) { font-size: 12px; }

  :deep(p) {
    margin: 8px 0;
    line-height: 1.6;
  }

  :deep(ul), :deep(ol) {
    margin: 8px 0;
    padding-left: 20px;
  }

  :deep(li) {
    margin: 4px 0;
  }

  :deep(blockquote) {
    margin: 16px 0;
    padding: 8px 16px;
    border-left: 4px solid var(--el-color-primary);
    background-color: var(--el-fill-color-extra-light);
    color: var(--el-text-color-regular);
  }

  :deep(code) {
    padding: 2px 4px;
    background-color: var(--el-fill-color-light);
    border-radius: 4px;
    font-family: 'Courier New', monospace;
    font-size: 0.9em;
  }

  :deep(pre) {
    margin: 16px 0;
    padding: 12px;
    background-color: var(--el-fill-color-light);
    border-radius: 6px;
    overflow-x: auto;

    code {
      padding: 0;
      background: none;
    }
  }

  :deep(table) {
    width: 100%;
    border-collapse: collapse;
    margin: 16px 0;

    th, td {
      padding: 8px 12px;
      border: 1px solid var(--el-border-color);
      text-align: left;
    }

    th {
      background-color: var(--el-fill-color-light);
      font-weight: 600;
    }
  }

  :deep(hr) {
    margin: 24px 0;
    border: none;
    border-top: 1px solid var(--el-border-color);
  }
}

// 错误状态
.error-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

// 响应式设计
@media (max-width: 1024px) {
  .view-mode {
    grid-template-columns: 1fr;

    .info-card {
      order: -1;
    }
  }
}

@media (max-width: 768px) {
  .report-detail-view {
    padding: 12px;
  }

  .page-header .header-content {
    flex-direction: column;
    align-items: stretch;

    .title-section {
      flex-direction: column;
      gap: 8px;

      .title-info .meta-info {
        flex-direction: column;
        align-items: flex-start;
        gap: 4px;
      }
    }

    .action-section {
      justify-content: center;
    }
  }

  .edit-mode .edit-card .edit-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .view-mode .content-card .content-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;

    .content-actions {
      justify-content: center;
    }
  }
}
</style>
